package cn.zhz.cloud.auth.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.zhz.cloud.auth.web.mapper.IPermissionMapper;
import cn.zhz.cloud.auth.web.model.dto.PermissionQueryDto;
import cn.zhz.cloud.auth.web.model.dto.PermissionSaveDto;
import cn.zhz.cloud.auth.web.model.po.PermissionPo;
import cn.zhz.cloud.auth.web.model.vo.PermissionVo;
import cn.zhz.cloud.auth.web.service.IPermissionService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限 Service实现类
 *
 * @author zhz
 * @since 2022-11-08
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<IPermissionMapper, PermissionPo> implements IPermissionService {


    /**
     * 分页查询
     *
     * @param queryDto 查询参数
     * @return
     */
    @Override
    public Page<PermissionVo> page(PermissionQueryDto queryDto) {
        long current = queryDto.getCurrent();
        long pageSize = queryDto.getSize();
        Page<PermissionPo> permissionPoPage = baseMapper.selectPage(new Page<>(current, pageSize), Wrappers.lambdaQuery(PermissionPo.class));
        List<PermissionVo> permissionVoList = permissionPoPage.getRecords().stream().map(permissionPo -> BeanUtil.copyProperties(permissionPo, PermissionVo.class)).collect(Collectors.toList());

        return new Page<PermissionVo>(current, pageSize)
                .setTotal(permissionPoPage.getTotal())
                .setRecords(permissionVoList);
    }

    /**
     * 详情
     *
     * @param id 主键
     * @return
     */
    @Override
    public PermissionVo info(Long id) {
        PermissionPo permissionPo = baseMapper.selectById(id);
        if (permissionPo == null) {
            // TODO
        }
        return BeanUtil.copyProperties(permissionPo, PermissionVo.class);
    }

    /**
     * 保存
     *
     * @param saveDto 保存参数
     * @return 主键
     */
    @Override
    public Long save(PermissionSaveDto saveDto) {
        PermissionPo permissionPo = BeanUtil.copyProperties(saveDto, PermissionPo.class);
        this.saveOrUpdate(permissionPo);
        return permissionPo.getId();
    }

    /**
     * 删除
     *
     * @param id 主键
     */
    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

    /**
     * 获取权限编码列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getPermissionCodeList(Long userId) {
        return baseMapper.getPermissionCodeListByUserId(userId);
    }
}
